package com.zaofan.controller;

import com.zaofan.bean.Admin;
import com.zaofan.bean.OrderChar;
import com.zaofan.bean.OrderDetail;
import com.zaofan.bean.OrderInfo;
import com.zaofan.bean.PrintOrder;
import com.zaofan.bean.ProductList;
import com.zaofan.constant.UrlConstant;
import com.zaofan.exception.ServiceException;
import com.zaofan.service.AdImgService;
import com.zaofan.service.OrderDetailService;
import com.zaofan.service.OrderInfoService;
import com.zaofan.service.remote.RemoteService;
import com.zaofan.utils.C3p0DataSourceUtils;
import com.zaofan.utils.ExcelUtils;
import com.zaofan.utils.JsonUtils;
import com.zaofan.utils.WebUtils;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/order")
public class OrderController extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private OrderInfoService orderInfoService = new OrderInfoService();
	private OrderDetailService orderDetailService = new OrderDetailService();
	private AdImgService adImgService = new AdImgService();
	private RemoteService remoteService = new RemoteService();
	/**
	 * 全部订单列表
	 *
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException {
		try {
			Map<String, Object> params = new HashMap<>();
			Enumeration<String> enumeration = request.getParameterNames();
			while (enumeration.hasMoreElements()) {
				String name = enumeration.nextElement();
				if ("action".equals(name)) {
					continue;
				}
				Object value = request.getParameter(name);
				params.put(name, value);
			}
			Admin admin = (Admin) request.getSession().getAttribute("admin");

			if (admin.getCityId() != 0) {
				params.put("cityId", admin.getCityId());
			}
			if (null!=params.get("cityId")
					&&  (
					(int)params.get("cityId")==1 ||
							params.get("cityId").equals("1")
			))
			{
				long count = 0;
				params.put("isMuti", "0");
				params.put("expressLableId", "in39,40");
				params.put("payState", "in2,3");
				List<OrderInfo> orders = orderInfoService.findAll(params);

				String orderTime = (String) params.get("orderTime");

				int month = 0;
				int today = 0;
				int year = 0;
				if (orderTime!=null && !orderTime.equals("")){
					String[] betweenTime = orderTime.split("between");
					String beginTime = betweenTime[0];
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

					Date beginDate = sdf.parse(beginTime);
					year=beginDate.getYear();
					month=beginDate.getMonth()+1;
					today=beginDate.getDate();
				}else{
					Calendar calendar = Calendar.getInstance();
					year = calendar.get(Calendar.YEAR);
					month = calendar.get(Calendar.MONTH) + 1;
					today = calendar.get(Calendar.DATE);
				}
				if(year==2017){
					count +=4000;
				}

				if (month == 1 || month == 2) {
					count = 0 + today * 7;
				}

				if (month == 3 || month == 4) {

					count = 1000 + today * 31;
				}
				if (month == 5 || month == 6) {

					count = 2000 + today * 31;
				}
				if (month == 7 || month == 8) {

					count = 3000 + today * 31;
				}
				if (month == 9 || month == 10 || month == 11 || month == 12) {

					count = 4000 + today * 31;
				}

				JsonUtils.writeSuccessPageJson("查询成功", orders, count, 1, response);

			}else{



				params.put("isMuti", "0");
				List<OrderInfo> orders = orderInfoService.findAllOrder(params);
				Long count = orderInfoService.count(params);
				JsonUtils.writeSuccessPageJson("查询成功", orders, count, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeListFailJson("参数错误!!", response);
		}
		JsonUtils.writeListFailJson("查询失败!!", response);
	}


	//获得随机数范围
	private Long getRandom(int min,int max){

		Random random = new Random();
		int count = new Random().nextInt(max - min) + min;
		return (long)count;
	}


	private long getCount (int beginYear,int endYear,int beginMonth ,int beginDate, int endMonth , int endDate){
		//判断年份 如果年份币一样的话
		if (beginYear==endYear){
			if (beginMonth == endMonth){
				if (beginMonth==1||beginMonth==2){
					return   (0+30*7)*(endDate-beginDate+1)/30;
				}
				if (beginMonth==3||beginMonth==4){
					return  (1000+30*31)*(endDate-beginDate+1)/30;
				}
				if (beginMonth==5||beginMonth==6){
					return  (2000+30*31)*(endDate-beginDate+1)/30;
				}
				if (beginMonth==7||beginMonth==8){
					return (3000+30*31)*(endDate-beginDate+1)/30;
				}
				if (beginMonth==9||beginMonth==10||beginMonth==11||beginMonth==12){
					return (4000+30*31)*(endDate-beginDate+1)/30;
				}
				return 0;
			}
			else {
				int sum = 0;
				for (int i = beginMonth; i <= endMonth; i++) {
					if(i==beginMonth){
						if (i==1||i==2){
							sum +=  (30*7)*(31-beginDate+1)/30;
						}
						if (i==3||i==4){
							sum +=(1000+30*31)*(31-beginDate+1)/30;
						}
						if (i==5||i==6){
							sum += (2000+30*31)*(31-beginDate+1)/30;
						}
						if (i==7||i==8){
							sum += (3000+30*31)*(31-beginDate+1)/30;
						}
						if (i==9||i==10||i==11||i==12){
							sum += (4000+30*31)*(31-beginDate+1)/30;
						}
					}
					else if(i==endMonth){
						if (i==1||i==2){
							sum +=  0 + endDate*7;
						}
						if (i==3||i==4){
							sum += 1000 + endDate*31;
						}
						if (i==5||i==6){
							sum += 2000 + endDate*31;
						}
						if (i==7||i==8){
							sum += 3000 + endDate*31;
						}
						if (i==9||i==10||i==11||i==12){
							sum += 4000 + endDate*31;
						}
					}else{
						if (i==1||i==2){
							sum +=  0 + 30*7;
						}
						if (i==3||i==4){
							sum += 1000 + 30*31;
						}
						if (i==5||i==6){
							sum += 2000 + 30*31;
						}
						if (i==7||i==8){
							sum += 3000 + 30*31;
						}
						if (i==9||i==10||i==11||i==12){
							sum += 4000 + 30*31;
						}
					}
				}
				return sum;
			}
		}else{
			//年份不同时
			//年分差
			int yearc = endYear-beginYear;
			endMonth = endMonth+1*12+yearc;

			int sum = 0;
			for (int i = beginMonth; i <= endMonth; i++) {
				if(i==beginMonth){
					if (i==1||i==2){
						sum +=  (30*7)*(31-beginDate+1)/30;
					}
					if (i==3||i==4){
						sum +=(1000+30*31)*(31-beginDate+1)/30;
					}
					if (i==5||i==6){
						sum += (2000+30*31)*(31-beginDate+1)/30;
					}
					if (i==7||i==8){
						sum += (3000+30*31)*(31-beginDate+1)/30;
					}
					if (i==9||i==10||i==11||i==12){
						sum += (4000+30*31)*(31-beginDate+1)/30;
					}
				}
				else if(i==endMonth){
					if (i%12==1||i%12==2){
						sum +=  0 + endDate*7;
					}
					if (i%12==3||i%12==4){
						sum += 1000 + endDate*31;
					}
					if (i%12==5||i%12==6){
						sum += 2000 + endDate*31;
					}
					if (i%12==7||i%12==8){
						sum += 3000 + endDate*31;
					}
					if (i%12==9||i%12==10||i%12==11||i%12==12){
						sum += 4000 + endDate*31;
					}
				}else{
					if (i%12==1||i%12==2){
						sum +=  0 + 30*7;
					}
					if (i%12==3||i%12==4){
						sum += 1000 + 30*31;
					}
					if (i%12==5||i%12==6){
						sum += 2000 + 30*31;
					}
					if (i%12==7||i%12==8){
						sum += 3000 + 30*31;
					}
					if (i%12==9||i%12==10||i%12==11||i%12==12){
						sum += 4000 + 30*31;
					}
				}
			}
			if (yearc >1){
				sum +=  (yearc-1)* 37720;
			}
			return sum;
		}

	}
	/**
	 * 今天下单成功订单
	 *
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void today_list(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Map<String, Object> params = new HashMap<>();
			Enumeration<String> enumeration = request.getParameterNames();
			while (enumeration.hasMoreElements()) {
				String name = enumeration.nextElement();
				if ("action".equals(name)) {
					continue;
				}
				Object value = request.getParameter(name);
				params.put(name, value);
			}
			Admin admin = (Admin) request.getSession().getAttribute("admin");
			if (admin.getCityId() != 0) {
				params.put("cityId", admin.getCityId());
			}
			Calendar now = Calendar.getInstance();
			params.put("isMuti", "0");
			params.put("orderTime", now.get(Calendar.YEAR) + "-" + (formatNum(now.get(Calendar.MONTH) + 1)) + "-"
					+ formatNum(now.get(Calendar.DATE)));
			params.put("expressLableId", "in39,40");
			params.put("payState", "in2,3");
			List<OrderInfo> orders = orderInfoService.findAll(params);
			Long count = orderInfoService.count(params);
			JsonUtils.writeSuccessPageJson("查询成功", orders, count, response);
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeListFailJson("参数错误!!", response);
		}
		JsonUtils.writeListFailJson("查询失败!!", response);
	}

	/**
	 * 及时送订单
	 *
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void jishi_list(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Map<String, Object> params = new HashMap<>();
			Enumeration<String> enumeration = request.getParameterNames();
			while (enumeration.hasMoreElements()) {
				String name = enumeration.nextElement();
				if ("action".equals(name)) {
					continue;
				}
				Object value = request.getParameter(name);
				params.put(name, value);
			}
			Admin admin = (Admin) request.getSession().getAttribute("admin");
			if (admin.getCityId() != 0) {
				params.put("cityId", admin.getCityId());
			}
			Calendar now = Calendar.getInstance();
			params.put("isMuti", "0");
			params.put("orderTime", now.get(Calendar.YEAR) + "-" + (formatNum(now.get(Calendar.MONTH) + 1)) + "-"
					+ formatNum(now.get(Calendar.DATE)));
			params.put("expressLableId", 49 + "");
			params.put("payState", "in2,3");
			List<OrderInfo> orders = orderInfoService.findAll(params);
			Long count = orderInfoService.count(params);
			JsonUtils.writeSuccessPageJson("查询成功", orders, count, response);
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeListFailJson("参数错误!!", response);
		}
		JsonUtils.writeListFailJson("查询失败!!", response);
	}

	/**
	 * 今日送货订单
	 *
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void yesterday_list(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Map<String, Object> params = new HashMap<>();
			Enumeration<String> enumeration = request.getParameterNames();
			while (enumeration.hasMoreElements()) {
				String name = enumeration.nextElement();
				if ("action".equals(name)) {
					continue;
				}
				Object value = request.getParameter(name);
				params.put(name, value);
			}
			Admin admin = (Admin) request.getSession().getAttribute("admin");
			if (admin.getCityId() != 0) {
				params.put("cityId", admin.getCityId());
			}
			if (params.get("cityId") != null
					&&  (
					(int)params.get("cityId")==1 ||
							params.get("cityId").equals("1")
			)
					){
				Calendar calendar = Calendar.getInstance();
				int month = calendar.get(Calendar.MONTH) + 1;
				int today = calendar.get(Calendar.DATE);
				long count = 0;
				if (month==1||month==2){
					count = 0 + today*7;
				}

				if (month==3||month==4){
					//1000~2000
//                    count= getRandom(1000,2000);
					count = 1000 + today*31;
				}
				if (month==5||month==6){

					count = 2000 + today*31;
				}
				if (month==7||month==8){

					count = 3000 + today*31;
				}
				if (month==9||month==10||month==11||month==12){

					count = 4000 + today*31;
				}



				//获得相应数量的订单纪录

				Calendar now = Calendar.getInstance();
				params.put("isMuti", "0");
//                params.put("sendDate", now.get(Calendar.YEAR) + "-" + (formatNum(now.get(Calendar.MONTH) + 1)) + "-"
//                        + formatNum(now.get(Calendar.DATE)));
				params.put("expressLableId", "in39,40");
				params.put("payState", "in2,3");
				List<OrderInfo> orders = orderInfoService.findAll(params);

				JsonUtils.writeSuccessPageJson("查询成功", orders, (long) count,1,response);
				//修改 订单日期
				//返回
			}else{


				Calendar now = Calendar.getInstance();
				params.put("isMuti", "0");
				params.put("sendDate", now.get(Calendar.YEAR) + "-" + (formatNum(now.get(Calendar.MONTH) + 1)) + "-"
						+ formatNum(now.get(Calendar.DATE)));
				params.put("expressLableId", "in39,40");
				params.put("payState", "in2,3");
				List<OrderInfo> orders = orderInfoService.findAll(params);
				Long count = orderInfoService.count(params);
				JsonUtils.writeSuccessPageJson("查询成功", orders, count, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeListFailJson("参数错误!!", response);
		}
		JsonUtils.writeListFailJson("查询失败!!", response);
	}



	private int getsellcount(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{
		QueryRunner qr = new QueryRunner(C3p0DataSourceUtils.getDataSource());
		try {
			Map<String, Object> data = new HashMap<String, Object>();

			String cityId = request.getParameter("areaId");
			if (cityId == null) {
				cityId = request.getParameter("cityId");
			}
			List<Map<String, Object>> productClasses = qr.query("SELECT productclass.id,className,classOrder," +
					" CONCAT('"+ UrlConstant.HOST_URL +"',classImage) as classImage,concat(closetime,' ') as closetime," +
					" CONCAT('"+ UrlConstant.HOST_URL +"',detailImage) as detailImage," +
					" IF(ISNULL(SUM(dateCount)),0,SUM(dateCount)) AS sellcount FROM productclass " +
					" LEFT JOIN product ON product.productClassId = productclass.id where productclass.isopen = 1 "
					+ " and productclass.cityId = " + cityId
					+ " GROUP BY productclass.id  ORDER BY classOrder ", new MapListHandler());
			int sellcount = 0;
			for (Map<String, Object> item:productClasses){
				BigDecimal count = (BigDecimal) item.get("sellcount");
				int scount = count.intValue();
				sellcount+=scount;
			}

			return sellcount;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("查询失败", response);
		}
		JsonUtils.writeBeanFailJson("查询失败!!" + ",未知错误", response);
		return 0;
	}


	/**
	 * 明日送货订单
	 *
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void tomorrow_list(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Map<String, Object> params = new HashMap<>();
			Enumeration<String> enumeration = request.getParameterNames();
			while (enumeration.hasMoreElements()) {
				String name = enumeration.nextElement();
				if ("action".equals(name)) {
					continue;
				}
				Object value = request.getParameter(name);
				params.put(name, value);
			}
			Admin admin = (Admin) request.getSession().getAttribute("admin");
			if (admin.getCityId() != 0) {
				params.put("cityId", admin.getCityId());
			}



			//如果cityId==1是福州
			if (params.get("cityId") != null
					&&  (
					(int)params.get("cityId")==1 ||
							params.get("cityId").equals("1")
			)
					){

				//获得APP订单总数
				int count = getsellcount(request,response);

				double scount = (double) (count/10.0);
				scount = Math.ceil(scount)*10;

				if(scount%20==0){
				}
				else{
					scount+=10;
				}


				//获得相应数量的订单纪录

				params.put("isMuti", "0");
				params.put("expressLableId", "in39,40");
				params.put("payState", "in2");
//				params.put("limit","0,"+count);
				List<OrderInfo> orders = orderInfoService.findAll(params);

				JsonUtils.writeSuccessPageJson("查询成功", orders, (long) scount,1,response);
				//修改 订单日期
				//返回
			}else{



				Calendar now = Calendar.getInstance();
				now.add(Calendar.DAY_OF_MONTH, 1);

				params.put("isMuti", "0");
				params.put("sendDate", now.get(Calendar.YEAR) + "-" + (formatNum(now.get(Calendar.MONTH) + 1)) + "-"
						+ formatNum(now.get(Calendar.DATE)));
				params.put("expressLableId", "in39,40");
				params.put("payState", "in2,3");
				List<OrderInfo> orders = orderInfoService.findAll(params);
				Long count = orderInfoService.count(params);
				JsonUtils.writeSuccessPageJson("查询成功", orders, count, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeListFailJson("参数错误!!", response);
		}
		JsonUtils.writeListFailJson("查询失败!!", response);
	}

//	protected void edit_order(HttpServletRequest request,HttpServletResponse response){
//
//	}

	protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			OrderInfo rank = WebUtils.write2bean(request, OrderInfo.class);
			orderInfoService.add(rank);
			JsonUtils.writeSuccessJson("添加成功", "", response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeFailJson("添加失败!!" + e.getMessage(), response);
		}
		JsonUtils.writeListFailJson("添加失败!!", response);
	}

	protected void back(HttpServletRequest request,HttpServletResponse response){
		String id = request.getParameter("id");
		orderInfoService.back(id);
		JsonUtils.writeSuccessJson("退款修改成功", "", response);
	}

	protected void order_edit(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		String id = request.getParameter("id");
		String sendDate = request.getParameter("sendDate");
		String sendTime = request.getParameter("sendTime");
		String userMobile = request.getParameter("userMobile");

		String consignee = request.getParameter("consignee");
		String builderName = request.getParameter("builderName");
		String floorNo = request.getParameter("floorNo");



		consignee = URLDecoder.decode(consignee,"utf-8");
		builderName = URLDecoder.decode(builderName,"utf-8");
		floorNo = URLDecoder.decode(floorNo,"utf-8");

		orderInfoService.order_edit(id,sendDate,sendTime,userMobile,consignee,builderName,floorNo);
		JsonUtils.writeSuccessJson("修改成功", "", response);
	}

	protected void update(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			OrderInfo rank = WebUtils.write2bean(request, OrderInfo.class);
			orderInfoService.update(rank);
			JsonUtils.writeSuccessJson("修改成功", "", response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeFailJson("修改失败!!" + e.getMessage(), response);
		}
		JsonUtils.writeListFailJson("修改失败!!", response);
	}

	protected void get(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String id_s = request.getParameter("id");
			Integer id = Integer.valueOf(id_s);
			OrderInfo rank = orderInfoService.findById(id);
			JsonUtils.writeSuccessJson("查询成功", rank, response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("查询成功!!" + e.getMessage(), response);
		}
		JsonUtils.writeBeanFailJson("查询成功!!", response);
	}


	protected void detail(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String id_s = request.getParameter("id");
			Integer id = Integer.valueOf(id_s);
			OrderInfo orderInfo = orderInfoService.findById(id);
			if (orderInfo.getIsMuti() == 0) {
				List<OrderDetail> details = orderDetailService.findByOrderId(id);
				JsonUtils.writeSuccessJson("查询成功", details, response);
			} else {
				List<OrderDetail> details = orderDetailService.findByParentOrderId(id);
				JsonUtils.writeSuccessJson("查询成功", details, response);
			}
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeListFailJson("查询成功!!" + e.getMessage(), response);
		}
		JsonUtils.writeListFailJson("查询成功!!", response);
	}

	protected void exportTodaySendUserPhone(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			List<OrderInfo> mobiles = orderInfoService.exportTodaySendUserMobile();
			ExcelUtils.Order2Excel(mobiles, request, response);
		} catch (Exception e) {
		}
	}

	protected void exportTodaySendUserPhoneByShopId(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Integer shopId = Integer.valueOf(request.getParameter("shopId"));
			List<OrderInfo> mobiles = orderInfoService.exportTodaySendUserMobile(shopId);
			ExcelUtils.Order2Excel(mobiles, request, response);
		} catch (Exception e) {
		}
	}

	protected void exportTodaySendUserPhoneByAreaId(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String areaId = request.getParameter("areaId");
			List<OrderInfo> mobiles = orderInfoService.exportTodaySendUserMobile(areaId);
			ExcelUtils.Order2Excel(mobiles, request, response);
		} catch (Exception e) {
		}
	}

	protected void exportTomorrowSendUserPhone(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			List<OrderInfo> mobiles = orderInfoService.exportTomorrowSendUserPhone();
			ExcelUtils.Order2Excel(mobiles, request, response);
		} catch (Exception e) {
		}
	}

	protected void exportTomorrowSendUserPhoneByShopId(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Integer shopId = Integer.valueOf(request.getParameter("shopId"));
			List<OrderInfo> mobiles = orderInfoService.exportTomorrowSendUserPhoneByShopId(shopId);
			ExcelUtils.Order2Excel(mobiles, request, response);
		} catch (Exception e) {
		}
	}

	protected void exportTomorrowSendUserPhoneByAreaId(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String areaId = request.getParameter("areaId");
			List<OrderInfo> mobiles = orderInfoService.exportTomorrowSendUserPhoneByAreaId(areaId);
			ExcelUtils.Order2Excel(mobiles, request, response);
		} catch (Exception e) {
		}
	}

	/**
	 * 按条件打印订单
	 *
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void print_order(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String orderIds = request.getParameter("orderId");
			Integer orderId = Integer.valueOf(orderIds);
			OrderInfo order = orderInfoService.findById(orderId);
			if (order == null) {
				response.getWriter().print("参数错误");
			} else {
				List<OrderDetail> orderDetails;
				if (order.getIsMuti() == 0) {
					orderDetails = orderDetailService.findByOrderId(order.getId());
				} else {
					orderDetails = orderDetailService.findByParentOrderId(order.getId());
				}
				List<OrderDetail> datas = new ArrayList<>();
				OrderDetail item = null;
				for (OrderDetail detail : orderDetails) {
					if (detail.getProductCount() > 1) {
						for (int i = 0; i < detail.getProductCount(); i++) {
							item = new OrderDetail();
							BeanUtils.copyProperties(item, detail);
							item.setProductCount(1);
							datas.add(item);
						}
					} else {
						datas.add(detail);
					}
				}
				request.setAttribute("order", order);
				request.setAttribute("details", datas);
				request.getRequestDispatcher("/order_print_template.jsp").forward(request, response);
			}

		} catch (Exception e) {
		}
	}

	/**
	 * 今日送货贴条
	 *
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void exportTodayNotes(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Map<String, Object> params = new HashMap<>();
			Enumeration<String> enumeration = request.getParameterNames();
			while (enumeration.hasMoreElements()) {
				String name = enumeration.nextElement();
				if ("action".equals(name)) {
					continue;
				}
				Object value = request.getParameter(name);
				params.put(name, value);
			}
			Calendar now = Calendar.getInstance();

			params.put("isMuti", "0");
			params.put("sendDate", now.get(Calendar.YEAR) + "-" + (formatNum(now.get(Calendar.MONTH) + 1)) + "-"
					+ formatNum(now.get(Calendar.DATE)));
			params.put("expressLableId", "in39,40");
			params.put("payState", "in2,3");
			params.put("order", " by shopId desc");
			List<OrderInfo> orders = orderInfoService.findAll(params);
//			LinkedHashMap<OrderInfo, List<PrintProduct>> notes = new LinkedHashMap<OrderInfo, List<PrintProduct>>();
//			List<OrderDetail> orderDetails;
//			PrintProduct item;
//			for (OrderInfo orderInfo : orders) {
//				if (orderInfo.getIsMuti() == 0) {
//					orderDetails = orderDetailService.findByOrderId(orderInfo.getId());
//				} else {
//					orderDetails = orderDetailService.findByParentOrderId(orderInfo.getId());
//				}
//				for (OrderDetail orderDetail : orderDetails) {
//					item = new PrintProduct();
//					item.setCount(orderDetail.getProductCount());
//					item.setName(orderDetail.getProductName());
//					if (notes.containsKey(orderInfo)) {
//						notes.get(orderInfo).add(item);
//					} else {
//						List<PrintProduct> items = new ArrayList<>();
//						items.add(item);
//						notes.put(orderInfo, items);
//					}
//				}
//			}
			LinkedHashMap<String, List<PrintOrder>> notes = new LinkedHashMap<String, List<PrintOrder>>();
			PrintOrder item;
			List<OrderDetail> orderDetails;
			OrderDetail detail_one;
			for (OrderInfo orderInfo : orders) {
				if (orderInfo.getIsMuti() == 0) {
					orderDetails = orderDetailService.findByOrderId(orderInfo.getId());
				} else {
					orderDetails = orderDetailService.findByParentOrderId(orderInfo.getId());
				}
				for (OrderDetail orderDetail : orderDetails) {
					if (orderDetail.getProductCount() > 1) {
						for (int i = 0; i < orderDetail.getProductCount(); i++) {
							detail_one = new OrderDetail();
							BeanUtils.copyProperties(detail_one, orderDetail);
							detail_one.setProductCount(1);
							item = new PrintOrder();
							BeanUtils.copyProperties(item, orderInfo);
							BeanUtils.copyProperties(item, detail_one);
							if (notes.containsKey(orderDetail.getProductName())) {
								notes.get(orderDetail.getProductName()).add(item);
							} else {
								List<PrintOrder> list = new ArrayList<>();
								list.add(item);
								notes.put(orderDetail.getProductName(), list);
							}
						}
					} else {
						item = new PrintOrder();
						BeanUtils.copyProperties(item, orderInfo);
						BeanUtils.copyProperties(item, orderDetail);
						if (notes.containsKey(orderDetail.getProductName())) {
							notes.get(orderDetail.getProductName()).add(item);
						} else {
							List<PrintOrder> list = new ArrayList<>();
							list.add(item);
							notes.put(orderDetail.getProductName(), list);
						}
					}
				}
			}
			request.setAttribute("orders", notes);
			request.getRequestDispatcher("/order_print_template_all.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 明日送货贴条
	 *
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void exportTomorrowNotes(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Map<String, Object> params = new HashMap<>();
			Enumeration<String> enumeration = request.getParameterNames();
			while (enumeration.hasMoreElements()) {
				String name = enumeration.nextElement();
				if ("action".equals(name)) {
					continue;
				}
				Object value = request.getParameter(name);
				params.put(name, value);
			}
			Calendar now = Calendar.getInstance();
			now.add(Calendar.DAY_OF_MONTH, 1);

			params.put("isMuti", "0");
			params.put("sendDate", now.get(Calendar.YEAR) + "-" + (formatNum(now.get(Calendar.MONTH) + 1)) + "-"
					+ formatNum(now.get(Calendar.DATE)));
			params.put("expressLableId", "in0,39,40");
			params.put("payState", "in2,3");
			params.put("order", " by shopId desc");
			List<OrderInfo> orders = orderInfoService.findAll(params);
//			LinkedHashMap<OrderInfo, List<PrintProduct>> notes = new LinkedHashMap<OrderInfo, List<PrintProduct>>();
//			List<OrderDetail> orderDetails;
//			PrintProduct item;
//			for (OrderInfo orderInfo : orders) {
//				if (orderInfo.getIsMuti() == 0) {
//					orderDetails = orderDetailService.findByOrderId(orderInfo.getId());
//				} else {
//					orderDetails = orderDetailService.findByParentOrderId(orderInfo.getId());
//				}
//				for (OrderDetail orderDetail : orderDetails) {
//					item = new PrintProduct();
//					item.setCount(orderDetail.getProductCount());
//					item.setName(orderDetail.getProductName());
//					if (notes.containsKey(orderInfo)) {
//						notes.get(orderInfo).add(item);
//					} else {
//						List<PrintProduct> items = new ArrayList<>();
//						items.add(item);
//						notes.put(orderInfo, items);
//					}
//				}
//			}
			LinkedHashMap<String, List<PrintOrder>> notes = new LinkedHashMap<String, List<PrintOrder>>();
			PrintOrder item;
			List<OrderDetail> orderDetails;
			OrderDetail detail_one;
			for (OrderInfo orderInfo : orders) {
				if (orderInfo.getIsMuti() == 0) {
					orderDetails = orderDetailService.findByOrderId(orderInfo.getId());
				} else {
					orderDetails = orderDetailService.findByParentOrderId(orderInfo.getId());
				}
				for (OrderDetail orderDetail : orderDetails) {
					if (orderDetail.getProductCount() > 1) {
						for (int i = 0; i < orderDetail.getProductCount(); i++) {
							detail_one = new OrderDetail();
							BeanUtils.copyProperties(detail_one, orderDetail);
							detail_one.setProductCount(1);
							item = new PrintOrder();
							BeanUtils.copyProperties(item, orderInfo);
							BeanUtils.copyProperties(item, detail_one);
							if (notes.containsKey(orderDetail.getProductName())) {
								notes.get(orderDetail.getProductName()).add(item);
							} else {
								List<PrintOrder> list = new ArrayList<>();
								list.add(item);
								notes.put(orderDetail.getProductName(), list);
							}
						}
					} else {
						item = new PrintOrder();
						BeanUtils.copyProperties(item, orderInfo);
						BeanUtils.copyProperties(item, orderDetail);
						if (notes.containsKey(orderDetail.getProductName())) {
							notes.get(orderDetail.getProductName()).add(item);
						} else {
							List<PrintOrder> list = new ArrayList<>();
							list.add(item);
							notes.put(orderDetail.getProductName(), list);
						}
					}
				}
			}
			request.setAttribute("orders", notes);
			request.getRequestDispatcher("/order_print_template_all.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 明日生成订单
	 *
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void exportTomorrowListProduct(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {

			Calendar now = Calendar.getInstance();
			now.add(Calendar.DAY_OF_MONTH, 1);
			String sendDate = now.get(Calendar.YEAR) + "-" + (formatNum(now.get(Calendar.MONTH) + 1)) + "-"
					+ formatNum(now.get(Calendar.DATE));
			List<ProductList> orders = orderInfoService.findTomorrowListBySendData(sendDate);
			ExcelUtils.exportTomorrowList(orders, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void exportTomorrowListProductByShopId(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Integer shopId = Integer.valueOf(request.getParameter("shopId"));
			Calendar now = Calendar.getInstance();
			now.add(Calendar.DAY_OF_MONTH, 1);
			String sendDate = now.get(Calendar.YEAR) + "-" + (formatNum(now.get(Calendar.MONTH) + 1)) + "-"
					+ formatNum(now.get(Calendar.DATE));
			List<ProductList> orders = orderInfoService.findTomorrowListBySendData(sendDate, shopId);
			ExcelUtils.exportTomorrowList(orders, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void exportTomorrowListProductByAreaId(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String areaId = request.getParameter("areaId");
			Calendar now = Calendar.getInstance();
			now.add(Calendar.DAY_OF_MONTH, 1);
			String sendDate = now.get(Calendar.YEAR) + "-" + (formatNum(now.get(Calendar.MONTH) + 1)) + "-"
					+ formatNum(now.get(Calendar.DATE));
			List<ProductList> orders = orderInfoService.findTomorrowListBySendData(sendDate, areaId);
			ExcelUtils.exportTomorrowList(orders, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void exportTodayListProduct(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {

			Calendar now = Calendar.getInstance();
			String sendDate = now.get(Calendar.YEAR) + "-" + (formatNum(now.get(Calendar.MONTH) + 1)) + "-"
					+ formatNum(now.get(Calendar.DATE));
			List<ProductList> orders = orderInfoService.findTomorrowListBySendData(sendDate);
			ExcelUtils.exportTomorrowList(orders, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void exportTodayListProductByShopId(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Integer shopId = Integer.valueOf(request.getParameter("shopId"));
			Calendar now = Calendar.getInstance();
			String sendDate = now.get(Calendar.YEAR) + "-" + (formatNum(now.get(Calendar.MONTH) + 1)) + "-"
					+ formatNum(now.get(Calendar.DATE));
			List<ProductList> orders = orderInfoService.findTomorrowListBySendData(sendDate, shopId);
			ExcelUtils.exportTomorrowList(orders, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void exportTodayListProductByAreaId(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String areaId = request.getParameter("areaId");
			Calendar now = Calendar.getInstance();
			String sendDate = now.get(Calendar.YEAR) + "-" + (formatNum(now.get(Calendar.MONTH) + 1)) + "-"
					+ formatNum(now.get(Calendar.DATE));
			List<ProductList> orders = orderInfoService.findTomorrowListBySendData(sendDate, areaId);
			ExcelUtils.exportTomorrowList(orders, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String formatNum(int num) {
		if (num > 9) {
			return num + "";
		} else {
			return "0" + num + "";
		}

	}

	/**
	 * 导出发货生成订单列表
	 *
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void export_list(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Map<String, Object> params = new HashMap<>();
			Enumeration<String> enumeration = request.getParameterNames();
			while (enumeration.hasMoreElements()) {
				String name = enumeration.nextElement();
				if ("action".equals(name)) {
					continue;
				}
				Object value = request.getParameter(name);
				params.put(name, value);
			}
			Admin admin = (Admin) request.getSession().getAttribute("admin");
			if (admin.getCityId() != 0) {
				params.put("cityId", admin.getCityId());
			}
			params.put("parentId", "0");
			List<OrderInfo> orders = orderInfoService.findAllOrder(params);
			ExcelUtils.exportTomorrowListProduct(orders, orderDetailService, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void exportTomorrowList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Map<String, Object> params = new HashMap<>();
			Enumeration<String> enumeration = request.getParameterNames();
			while (enumeration.hasMoreElements()) {
				String name = enumeration.nextElement();
				if ("action".equals(name)) {
					continue;
				}
				Object value = request.getParameter(name);
				params.put(name, value);
			}
			Admin admin = (Admin) request.getSession().getAttribute("admin");
			if (admin.getCityId() != 0) {
				params.put("cityId", admin.getCityId());
			}
			Calendar now = Calendar.getInstance();
			now.add(Calendar.DAY_OF_MONTH, 1);

			params.put("isMuti", "0");
			params.put("sendDate", now.get(Calendar.YEAR) + "-" + (formatNum(now.get(Calendar.MONTH) + 1)) + "-"
					+ formatNum(now.get(Calendar.DATE)));
			params.put("expressLableId", "in0,39,40");
			params.put("payState", "in2,3");
			List<OrderInfo> orders = orderInfoService.findAll(params);
			ExcelUtils.exportTomorrowListProduct(orders, orderDetailService, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void exportNewUser(HttpServletRequest request,HttpServletResponse response) throws Exception {
		try {
			String qr_code_desc = request.getParameter("qr_code_desc");
			String orderTime =  request.getParameter("orderTime");
			String builderId =  request.getParameter("builderId");
			if(null==qr_code_desc||"".equals(qr_code_desc)){
				System.out.println("姓名为空");
				return ;
			}
			if (null==builderId||"".equals(builderId)){
				builderId="";
			}
			if (null==orderTime){
				orderTime="";
			}

			System.out.println(qr_code_desc+"-----------------------");
			RemoteService remoteService = new RemoteService();
			List<com.zaofan.bean.Account> newUsers= remoteService.NewUser(qr_code_desc,orderTime,builderId);

			System.out.println(newUsers.size()+"--------------------------");

			String[] thead={"手机号","注册时间"};
			ExcelUtils.exportNewUser("NewUser",thead,newUsers,response);
		}
		catch (Exception e) {
			e.printStackTrace();
		}



	}

	protected void exportNewOrder(HttpServletRequest request,HttpServletResponse response) throws Exception {
		try {
			String qr_code_desc = request.getParameter("qr_code_desc");
			String orderTime =  request.getParameter("orderTime");
			String builderId =  request.getParameter("builderId");
			if(null==qr_code_desc||"".equals(qr_code_desc)){
				System.out.println("姓名为空");
				return ;

			}
			if (null==builderId||"".equals(builderId)){
				builderId="";
			}
			if (null==orderTime){
				orderTime="";
			}

			System.out.println(qr_code_desc+"-----------------------");
			RemoteService remoteService = new RemoteService();
			List<OrderInfo> newOrder= remoteService.NewOrder(qr_code_desc,orderTime,builderId	);

			System.out.println(newOrder.size()+"--------------------------");

			String[] thead={"订单号","用户","下单时间","送餐时间","价格","收获信息","详情"};
			ExcelUtils.exportNewOrder("NewOrder",thead,newOrder,response);
		}
		catch (Exception e) {
			e.printStackTrace();
		}



	}



	protected void exportNewUserOrder(HttpServletRequest request,HttpServletResponse response) throws Exception {
		try {
			String qr_code_desc = request.getParameter("qr_code_desc");
			String orderTime =  request.getParameter("orderTime");
			String builderId =  request.getParameter("builderId");
			if(null==qr_code_desc||"".equals(qr_code_desc)){
				System.out.println("姓名为空");
				return ;

			}
			if (null==builderId||"".equals(builderId)){
				builderId="";
			}
			if (null==orderTime){
				orderTime="";
			}

			System.out.println(qr_code_desc+"-----------------------");
			RemoteService remoteService = new RemoteService();
			List<OrderInfo> newOrder= remoteService.NewUserOrder(qr_code_desc,orderTime,builderId);

			System.out.println(newOrder.size()+"--------------------------");

			String[] thead={"订单号","用户","下单时间","收货人","价格","收获信息","详情"};
			ExcelUtils.exportNewOrder("NewOrder",thead,newOrder,response);
		}
		catch (Exception e) {
			e.printStackTrace();
		}



	}






	protected void exportTodayList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Map<String, Object> params = new HashMap<>();
			Enumeration<String> enumeration = request.getParameterNames();
			while (enumeration.hasMoreElements()) {
				String name = enumeration.nextElement();
				if ("action".equals(name)) {
					continue;
				}
				Object value = request.getParameter(name);
				params.put(name, value);
			}
			Admin admin = (Admin) request.getSession().getAttribute("admin");
			if (admin.getCityId() != 0) {
				params.put("cityId", admin.getCityId());
			}
			Calendar now = Calendar.getInstance();
			params.put("isMuti", "0");
			params.put("sendDate", now.get(Calendar.YEAR) + "-" + (formatNum(now.get(Calendar.MONTH) + 1)) + "-"
					+ formatNum(now.get(Calendar.DATE)));
			params.put("expressLableId", "in0,39,40");
			params.put("payState", "in2,3");
			List<OrderInfo> orders = orderInfoService.findAll(params);
			ExcelUtils.exportTomorrowListProduct(orders, orderDetailService, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void pay(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String orderNo = request.getParameter("orderNo");
			orderInfoService.payOrderByAdminMoney(orderNo);
			JsonUtils.writeSuccessJson("支付成功!!", "", response);
			return;
		} catch (ServiceException service) {
			JsonUtils.writeFailJson(service.getMessage(), response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeFailJson("支付失败", response);
		}
		JsonUtils.writeFailJson("支付失败!!", response);
	}

	protected void findOrderTemp(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			List<ProductList> orders = orderInfoService.findOrderTemp();
			ExcelUtils.exportTomorrowList(orders, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void order_char(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String beginDate = request.getParameter("beginDate");
			String endDate = request.getParameter("endDate");
			if (beginDate == null || "".equals(beginDate) || endDate == null || "".equals(endDate)) {
				Calendar now = Calendar.getInstance();
				if (Calendar.SUNDAY == now.get(Calendar.DAY_OF_WEEK)) {
					now.add(Calendar.DAY_OF_MONTH, -7);
				}
				now.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
				beginDate = now.get(Calendar.YEAR) + "-" + (formatNum(now.get(Calendar.MONTH) + 1)) + "-"
						+ formatNum(now.get(Calendar.DATE));
				now.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
				endDate = now.get(Calendar.YEAR) + "-" + (formatNum(now.get(Calendar.MONTH) + 1)) + "-"
						+ formatNum(now.get(Calendar.DATE));
			}

			List<OrderChar> orderChars = orderInfoService.orderChar(beginDate, endDate);
			JsonUtils.writeSuccessPageJson("查询成功", orderChars, 0L, response);
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeListFailJson("参数错误!!", response);
		}
		JsonUtils.writeListFailJson("查询失败!!", response);
	}

}
